package com.dries.security.browser.service.impl;

import com.dries.security.core.properties.SecurityCoreConstants;
import com.dries.security.core.validate.code.captcha.SysCaptcha;
import com.dries.security.core.validate.code.captcha.enums.ValidateCodeType;
import com.dries.security.core.validate.code.impl.ValidateCodeMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/8 17:09
 */
@Component
public class SessionValidateCodeService implements ValidateCodeMapper {

    /***
     * @Description: save 保存验证码
     * @return: void
     * @date: 2019/11/24 18:36
     *
     * @param request
     * @param code
     * @param validateCodeType*/
    @Override
    public void save(ServletWebRequest request, SysCaptcha code, ValidateCodeType validateCodeType) {
        SecurityCoreConstants.sessionStrategy.setAttribute(request, getSessionKey(validateCodeType), code);
    }

    /***
     * @Description: get 获取验证码
     * @param: [request, validateCodeType]
     * @date: 2019/11/24 18:37
     *
     * @param request
     * @param validateCodeType*/
    @Override
    public SysCaptcha get(ServletWebRequest request, ValidateCodeType validateCodeType) {

        String sessionKey = getSessionKey(validateCodeType);

        return (SysCaptcha) SecurityCoreConstants.sessionStrategy.getAttribute(request, sessionKey);
    }

    /***
     * @Description: remove 移除验证码
     * @return: void
     * @date: 2019/11/24 18:39
     *
     * @param request
     * @param validateCodeType*/
    @Override
    public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
        SecurityCoreConstants.sessionStrategy.removeAttribute(request, getSessionKey(validateCodeType));
    }

    /***
     * @Description: getSessionKey 构建验证码放入session时的key; 在保存的时候也使用该key
     * @param: [validateCodeType]
     * @return: java.lang.String
     * @date: 2019/11/24 20:51
     **/
    private String getSessionKey(ValidateCodeType validateCodeType) {
        return SecurityCoreConstants.SESSION_KEY_PREFIX + validateCodeType.toString().toUpperCase();
    }
}
